package com.ugrow.ugrowcommunity.activity.moments;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.DialogFragment;

import com.ugrow.ugrowcommunity.R;
import com.ugrow.ugrowcommunity.databinding.FragmentCommendInputDialogBinding;

public class CommendInputDialogFragment extends DialogFragment {

    private FragmentCommendInputDialogBinding mBinding;
    private int mAllowableErrorHeight;

    public CommendInputDialogFragment() {
        // Required empty public constructor
    }

    private String mContent;
    private int mLastDiff = 0;
    public static final String CONTENT = "content";

    public static CommendInputDialogFragment newInstance(String content) {
        CommendInputDialogFragment fragment = new CommendInputDialogFragment();
        Bundle args = new Bundle();
        args.putString(CONTENT, content);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mContent = getArguments().getString(CONTENT);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Window window = getDialog().getWindow();
        super.onActivityCreated(savedInstanceState);
        getDialog().setCancelable(true);
        getDialog().setCanceledOnTouchOutside(true);
        //设置背景为透明
        window.setWindowAnimations(R.style.AnimBottom);
        window.setBackgroundDrawable(ContextCompat.getDrawable(getContext(), android.R.color.transparent));
        //去除阴影
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        layoutParams.dimAmount = 0.5f;
        window.setAttributes(layoutParams);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE|WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dismissDialog();
            }
        });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mBinding = DataBindingUtil.bind(inflater.inflate(R.layout.fragment_commend_input_dialog, container, false));
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding.mTvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = mBinding.mEditText.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(requireContext(), "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mOnDisMissCallBack != null) {
                    mOnDisMissCallBack.saveCommend();
                }
                dismissDialog();
            }
        });
        mBinding.mEditText.setFocusable(true);
        mBinding.mEditText.setFocusableInTouchMode(true);
        mBinding.mEditText.requestFocus();
        mBinding.mEditText.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                Rect r = new Rect();
                //获取当前界面可视部分
                getActivity().getWindow().getDecorView().getRootView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight = getActivity().getWindow().getDecorView().getRootView().getHeight();

                //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                mAllowableErrorHeight = screenHeight - r.bottom;
                setOnKeyBordListener();
            }
        },100);
        mBinding.mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String content = mBinding.mEditText.getText().toString();
                if(mOnDisMissCallBack != null){
                    mOnDisMissCallBack.onCommendTextChanged(content);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //设置已经填过的文字，以及移动光标
        mBinding.mEditText.setText(mContent);
        if(!TextUtils.isEmpty(mContent) && mContent.length() > 0){
            mBinding.mEditText.setSelection(mContent.length());
        }
    }

    private void setOnKeyBordListener() {
        requireActivity().getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                try {
                    Rect r = new Rect();
                    //获取当前界面可视部分
                    requireActivity().getWindow().getDecorView().getRootView().getWindowVisibleDisplayFrame(r);
                    //获取屏幕的高度
                    int screenHeight = getActivity().getWindow().getDecorView().getRootView().getHeight();

                    //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                    int heightDifference = screenHeight - r.bottom;
                    if (heightDifference > mAllowableErrorHeight && mLastDiff >= 0) {
                        //开软键盘
                    } else {
                        //关闭软键盘
                        dismissDialog();
                    }
                    mLastDiff = heightDifference;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        mBinding.mRoot.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
                Rect r = new Rect();
                //获取当前界面可视部分
                getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight = getActivity().getWindow().getDecorView().getRootView().getHeight();

                //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                int heightDifference = screenHeight - r.bottom;
                if (heightDifference <= mAllowableErrorHeight && mLastDiff >= 0) {
                    //开软键盘
                } else {
                    //关闭软键盘
                    dismissDialog();
                }
                Log.d("yanjin","heightDifference = "+heightDifference+" mLastDiff="+mLastDiff);
                mLastDiff = heightDifference;
            }
        });
    }

    private void dismissDialog() {
        if (mOnDisMissCallBack != null) {
            mOnDisMissCallBack.onDismiss();
        }
        dismissAllowingStateLoss();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        mLastDiff = 0;
    }

    public interface OnDisMissCallBack {
        void onDismiss();
        void saveCommend();
        void onCommendTextChanged(String contend);
    }

    private OnDisMissCallBack mOnDisMissCallBack;

    public void setOnDisMissCallBack(OnDisMissCallBack mOnDisMissCallBack) {
        this.mOnDisMissCallBack = mOnDisMissCallBack;
    }
}